#include "GameGUI.h"
#include <OgreHardwarePixelBuffer.h>
#include <fstream>
#include "GameApp.h"

GameGUI *gpGUI = 0;

std::stringstream sysout = std::stringstream();
std::stringstream frontout = std::stringstream();

//-------------------------------------------------------------------------------------
GameGUI::GameGUI(Ogre::RenderWindow *window)
	: mpRenderer(0), mpWindow(window), mpSysOutputWnd(0), mpTextOutput(0), mpQuitButton(0), mpVideoSettings(0), mbInit(true), mSaveExists(false)
{
}
//-------------------------------------------------------------------------------------
GameGUI::~GameGUI(void)
{
	gpGUI = 0;
	delete mTexts;
}
//-------------------------------------------------------------------------------------
void GameGUI::init(VideoSettings *videoSettings)
{
	mpRenderer = &CEGUI::OgreRenderer::bootstrapSystem();
	mpVideoSettings = videoSettings;
	mTexts = new SettingsManager("level/texts.xml");

	// Assign ressources
	CEGUI::Imageset::setDefaultResourceGroup("Imagesets");
	CEGUI::Font::setDefaultResourceGroup("Fonts");
	CEGUI::Scheme::setDefaultResourceGroup("Schemes");
	CEGUI::WidgetLookManager::setDefaultResourceGroup("LookNFeel");
	CEGUI::WindowManager::setDefaultResourceGroup("Layouts");


	// Set the layout of the GUI7
	CEGUI::ImagesetManager::getSingleton().create("sword.imageset");
	CEGUI::ImagesetManager::getSingleton().create("gun.imageset");
	CEGUI::ImagesetManager::getSingleton().create("macaroni.imageset");
	CEGUI::ImagesetManager::getSingleton().create("tutor.imageset");
	CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
	CEGUI::SchemeManager::getSingleton().create("VanillaSkin.scheme");
	CEGUI::SchemeManager::getSingleton().create("SleekSpace.scheme");
	CEGUI::SchemeManager::getSingleton().create("SleekSpaceR.scheme");
	CEGUI::SchemeManager::getSingleton().create("SleekSpaceY.scheme");
	CEGUI::SchemeManager::getSingleton().create("WindowsLook.scheme");
	CEGUI::System::getSingleton().setDefaultMouseCursor("SleekSpace", "MouseArrow");
	CEGUI::Font &font0 = CEGUI::FontManager::getSingleton().create("DejaVuSans-10.font");
    CEGUI::Font &font1 = CEGUI::FontManager::getSingleton().create("FairChar-30.font");
	CEGUI::Font &font2 = CEGUI::FontManager::getSingleton().create("Batang-26.font");
	CEGUI::Font &font3 = CEGUI::FontManager::getSingleton().create("fkp-16.font");

	CEGUI::WindowManager &wmgr = CEGUI::WindowManager::getSingleton();
	CEGUI::Window *sheet = wmgr.createWindow("DefaultWindow", "GameGUI");


	// Create output window for debuging
	mpSysOutputWnd = static_cast<CEGUI::MultiLineEditbox*>(wmgr.createWindow("TaharezLook/MultiLineEditbox", "OutputWindow"));
	mpSysOutputWnd->setSize(CEGUI::UVector2(CEGUI::UDim(0.4f, 0), CEGUI::UDim(0.3f, 0)));
	mpSysOutputWnd->setPosition(CEGUI::UVector2(CEGUI::UDim(0.0f, 0), CEGUI::UDim(0.0f, 0)));
	mpSysOutputWnd->setAlpha(0.4f);
	mpSysOutputWnd->setReadOnly(true);
	mpSysOutputWnd->setText("-- Voo --");
	mpSysOutputWnd->setAlwaysOnTop(true);

	sheet->addChildWindow(mpSysOutputWnd);

	// Create main menu
	mpMainMenu = wmgr.createWindow("DefaultWindow", "GameGUI/MainMenu");

	// Create menu button to continue the game from the last save point
	mpContinueButton = static_cast<CEGUI::PushButton*>(wmgr.createWindow("TaharezLook/Button", "ContinueButton"));
	mpContinueButton->setSize(CEGUI::UVector2(CEGUI::UDim(0.25f, 0), CEGUI::UDim(0.1f, 0)));
	mpContinueButton->setPosition(CEGUI::UVector2(CEGUI::UDim(0.375f, 0), CEGUI::UDim(0.25f, 0)));
	mpContinueButton->setText("Continue");
	mpContinueButton->setEnabled(false);

	mpMainMenu->addChildWindow(mpContinueButton);

	// Create menu button to start new game
	mpLoadGameButton = static_cast<CEGUI::PushButton*>(wmgr.createWindow("TaharezLook/Button", "LoadGameButton"));
	mpLoadGameButton->setSize(CEGUI::UVector2(CEGUI::UDim(0.25f, 0), CEGUI::UDim(0.1f, 0)));
	mpLoadGameButton->setPosition(CEGUI::UVector2(CEGUI::UDim(0.375f, 0), CEGUI::UDim(0.35f, 0)));
	mpLoadGameButton->setText("Load Game");
	
	// Check if a savegame exists
	ifstream in;
	in.open("saves/savegame.xml");
	mSaveExists = in.good();
	if (!mSaveExists) mpLoadGameButton->setEnabled(false);
	in.close();

	mpMainMenu->addChildWindow(mpLoadGameButton);

	// Create menu button to start new game
	mpNewGameButton = static_cast<CEGUI::PushButton*>(wmgr.createWindow("TaharezLook/Button", "NewGameButton"));
	mpNewGameButton->setSize(CEGUI::UVector2(CEGUI::UDim(0.25f, 0), CEGUI::UDim(0.1f, 0)));
	mpNewGameButton->setPosition(CEGUI::UVector2(CEGUI::UDim(0.375f, 0), CEGUI::UDim(0.45f, 0)));
	mpNewGameButton->setText("New Game");

	mpMainMenu->addChildWindow(mpNewGameButton);

	// Create menu button to open options menu
	mpOptionsButton = static_cast<CEGUI::PushButton*>(wmgr.createWindow("TaharezLook/Button", "OptionsButton"));
	mpOptionsButton->setSize(CEGUI::UVector2(CEGUI::UDim(0.25f, 0), CEGUI::UDim(0.1f, 0)));
	mpOptionsButton->setPosition(CEGUI::UVector2(CEGUI::UDim(0.375f, 0), CEGUI::UDim(0.55f, 0)));
	mpOptionsButton->setText("Options");

	mpMainMenu->addChildWindow(mpOptionsButton);

	// Create menu button to quit the game
	mpQuitButton = static_cast<CEGUI::PushButton*>(wmgr.createWindow("TaharezLook/Button", "QuitButton"));
	mpQuitButton->setSize(CEGUI::UVector2(CEGUI::UDim(0.25f, 0), CEGUI::UDim(0.1f, 0)));
	mpQuitButton->setPosition(CEGUI::UVector2(CEGUI::UDim(0.375f, 0), CEGUI::UDim(0.65f, 0)));
	mpQuitButton->setText("Quit");

	mpMainMenu->addChildWindow(mpQuitButton);

	sheet->addChildWindow(mpMainMenu);


	// Create text output at the middle of the screen
	mpTextOutput = static_cast<CEGUI::Window*>(wmgr.createWindow("TaharezLook/StaticText", "TextOutput"));
	mpTextOutput->setSize(CEGUI::UVector2(CEGUI::UDim(1.0f, 0), CEGUI::UDim(0.1f, 0)));
	mpTextOutput->setPosition(CEGUI::UVector2(CEGUI::UDim(0.0f, 0), CEGUI::UDim(0.20f, 0)));
	mpTextOutput->setFont(&font1);
	mpTextOutput->setText("VOO");
	mpTextOutput->setProperty("TextColours", "tl:FFFF0000 tr:FFFF0000 bl:FFFF0000 br:FFFF0000");
	mpTextOutput->setProperty("VertFormatting", "VertCentred");
	mpTextOutput->setProperty("HorzFormatting", "HorzCentred");
	mpTextOutput->setProperty("BackgroundEnabled", "false");
	mpTextOutput->setProperty("FrameEnabled", "false");
	mpTextOutput->setAlpha(0.0f);

	sheet->addChildWindow(mpTextOutput);

	// Load Class Selection window
	mpClassSelection = CEGUI::WindowManager::getSingleton().loadWindowLayout("ClassSelection.layout");
	mpMeleeSelection = static_cast<CEGUI::PushButton*>(mpClassSelection->getChild("ClassSelection/Sword"));
	mpRangedSelection = static_cast<CEGUI::PushButton*>(mpClassSelection->getChild("ClassSelection/Gun"));

	sheet->addChildWindow(mpClassSelection);

	//load story text display window
	this->mpStoryWindow = CEGUI::WindowManager::getSingleton().loadWindowLayout("TextDisplay.layout");
	this->mpStoryDisplay = static_cast<CEGUI::Window*>(mpStoryWindow->getChild("TextDisplay/Text"));
	this->mpStoryImage = static_cast<CEGUI::Window*>(mpStoryWindow->getChild("TextDisplay/Image"));
	this->mpStoryButton = static_cast<CEGUI::PushButton*>(mpStoryWindow->getChild("TextDisplay/Button"));

	sheet->addChildWindow(mpStoryWindow);

	// Load skill menu
	mpSkillMenu = CEGUI::WindowManager::getSingleton().loadWindowLayout("SkillMenu3.layout");
	mpSP = static_cast<CEGUI::Window*>(mpSkillMenu->getChild("SkillMenu/SP"));
	mpClass = static_cast<CEGUI::Window*>(mpSkillMenu->getChild("SkillMenu/Class"));
	mpHealthBar = static_cast<CEGUI::ProgressBar*>(mpSkillMenu->getChild("SkillMenu/Health")->getChild("SkillMenu/Health/Bar"));
	mpEnergyBar = static_cast<CEGUI::ProgressBar*>(mpSkillMenu->getChild("SkillMenu/Energy")->getChild("SkillMenu/Energy/Bar"));
	mpCombatBar = static_cast<CEGUI::ProgressBar*>(mpSkillMenu->getChild("SkillMenu/Combat")->getChild("SkillMenu/Combat/Bar"));

	sheet->addChildWindow(mpSkillMenu);

	// create heads up display
	mpHUD = CEGUI::WindowManager::getSingleton().loadWindowLayout("hud.layout");
	mpHUDHealth = static_cast<CEGUI::ProgressBar*>(mpHUD->getChild("HUD/health")->getChild("HUD/health/bar"));
	mpHUDEnergy = static_cast<CEGUI::ProgressBar*>(mpHUD->getChild("HUD/energy")->getChild("HUD/energy/bar"));
	mpHUDEXP = static_cast<CEGUI::ProgressBar*>(mpHUD->getChild("HUD/exp")->getChild("HUD/exp/bar"));
	mpHUDButton = static_cast<CEGUI::PushButton*>(mpHUD->getChild("HUD/menu")->getChild("HUD/menu/button"));

	sheet->addChildWindow(mpHUD);


	// Load options menu
	mpOptionsMenu = CEGUI::WindowManager::getSingleton().loadWindowLayout("OptionsMenu.layout");

	Ogre::StringVector resList = mpVideoSettings->getResolutionList();
	Ogre::StringVector fsaaList = mpVideoSettings->getFSAAList();

	// Add all possible resolutions to the options menu
	CEGUI::Combobox *resBox = static_cast<CEGUI::Combobox*>(mpOptionsMenu->getChild("OptionsMenu/ResolutionComboBox"));
	for (int i = 0; i < (int)resList.size(); ++i)
	{
		resBox->addItem(new CEGUI::ListboxTextItem(resList.at(i).c_str()));
	}

	// Add all possible FSAA values to the options menu
	CEGUI::Combobox *fsaaBox = static_cast<CEGUI::Combobox*>(mpOptionsMenu->getChild("OptionsMenu/FSAAComboBox"));
	for (int i = 0; i < (int)fsaaList.size(); ++i)
	{
		fsaaBox->addItem(new CEGUI::ListboxTextItem(fsaaList.at(i).c_str()));
	}

	// Check if VSync is supported
	CEGUI::Checkbox *checkBox = static_cast<CEGUI::Checkbox*>(mpOptionsMenu->getChild("OptionsMenu/VSyncCheckBox"));
	if (!mpVideoSettings->getVSync()) checkBox->setEnabled(false);

	sheet->addChildWindow(mpOptionsMenu);


	CEGUI::System::getSingleton().setGUISheet(sheet);

	mpMainMenu->activate();
	mpSysOutputWnd->hide();
	mpSkillMenu->hide();
	mpStoryWindow->hide();
	mpClassSelection->hide();
	mpOptionsMenu->hide();
	mpHUD->show();

	CEGUI::MouseCursor::getSingleton().setPosition(CEGUI::Point(0.0f, 0.0f));
	
	mpContinueButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::continueGame, this));
	mpLoadGameButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::loadGame, this));
	mpNewGameButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::newGame, this));
	mpOptionsButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::openOptions, this));
	mpQuitButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::quitGame, this));
	mpHUDButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::openSkillMenu, this));
	mpStoryButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::storyButton, this));
	mpMeleeSelection->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::selectMelee, this));
	mpRangedSelection->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::selectRanged, this));

	CEGUI::Window *button = mpSkillMenu->getChild("SkillMenu/Button");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::closeSkillMenu, this));
	button = mpSkillMenu->getChild("SkillMenu/Health")->getChild("SkillMenu/Health/Button");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::increaseHealth, this));
	button = mpSkillMenu->getChild("SkillMenu/Energy")->getChild("SkillMenu/Energy/Button");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::increaseEnergy, this));
	button = mpSkillMenu->getChild("SkillMenu/Combat")->getChild("SkillMenu/Combat/Button");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::increaseCombat, this));

	button = mpOptionsMenu->getChild("OptionsMenu/OKButton");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::submitOptions, this));
	button = mpOptionsMenu->getChild("OptionsMenu/CancelButton");
	button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&GameGUI::cancelOptions, this));

	gpGUI = this;
}
//-------------------------------------------------------------------------------------
bool GameGUI::openWeaponSelect(void)
{
	gpApp->changeState(State_Pause);
	this->mpClassSelection->show();
	this->mpClassSelection->activate();

	return true;
}
//-------------------------------------------------------------------------------------
void GameGUI::update(Ogre::Real elapsedTime)
{
	// Update system output window
	if (sysout.str().length())
	{
		// Write output that was send last frame
		mpSysOutputWnd->setText(mpSysOutputWnd->getText() + CEGUI::String(sysout.str()));
		sysout.str("");

		// Scroll to the end
		CEGUI::Scrollbar* scrol = mpSysOutputWnd->getVertScrollbar();
		scrol->setScrollPosition(scrol->getDocumentSize() - scrol->getPageSize());
	}

	// Update text at the front
	if (frontout.str().length())
	{
		// Write output that was send last frame
		mpTextOutput->setText(CEGUI::String(frontout.str()));
		mpTextOutput->setAlpha(0.95f);
		if (strcmp(CEGUI::String(frontout.str()).c_str(), "GAME OVER"))
			mpTextOutput->setAlpha(1.0f);
		frontout.str("");
	}
	else
	{
		float alpha = mpTextOutput->getAlpha() - 2 * elapsedTime * (1.0f - mpTextOutput->getAlpha());
		mpTextOutput->setAlpha(alpha);
	}

	//update HUD
	float maxH = (float)gpApp->mpGameLogic->getCharacter()->getResources(RES_HEALTH_CAP);
	float health = (float)gpApp->mpGameLogic->getCharacter()->getResources(RES_HEALTH);
	float energy = (float)gpApp->mpGameLogic->getCharacter()->getResources(RES_ENERGY);
	float maxE = (float)gpApp->mpGameLogic->getCharacter()->getResources(RES_HEALTH_CAP);
	float maxEXP = 1000.0f;
	float exp = (float)gpApp->mpGameLogic->getCharacter()->getEXP();

	this->mpHUDHealth->setProgress(health/maxH);
	this->mpHUDEnergy->setProgress(energy/maxE);
	this->mpHUDEXP->setProgress(exp/maxEXP);

	CEGUI::System::getSingleton().injectTimePulse(elapsedTime);
}
//-------------------------------------------------------------------------------------
void GameGUI::restoreSettings(void)
{
	OpenGLConfig *config = mpVideoSettings->getCurOpenGLSettings();

	// Set current resolution
	mpOptionsMenu->getChild("OptionsMenu/ResolutionComboBox")->setText(config->resolution->c_str());

	// Set current FSAA
	mpOptionsMenu->getChild("OptionsMenu/FSAAComboBox")->setText(config->fsaa->c_str());

	// Set current VSync option
	CEGUI::Checkbox *checkBox = static_cast<CEGUI::Checkbox*>(mpOptionsMenu->getChild("OptionsMenu/VSyncCheckBox"));
	if (strcmp(config->vsync->c_str(), "Yes") == 0) checkBox->setSelected(true);

	// Set current fullscreen option
	checkBox = static_cast<CEGUI::Checkbox*>(mpOptionsMenu->getChild("OptionsMenu/FullscreenCheckBox"));
	if (strcmp(config->fullscreen->c_str(), "Yes") == 0) checkBox->setSelected(true);
}
//-------------------------------------------------------------------------------------
void GameGUI::setSaveExists(const bool exists)
{
	mSaveExists = exists;
}
//-------------------------------------------------------------------------------------
void GameGUI::onGlobalCharacterKey(const CEGUI::uint key)
{
	GameState state = gpApp->getState();

	// Open and close the menu
	if (key == 1)
	{
		if (mpMainMenu->isVisible())
		{
			if (state != State_Initializing)
			{
				mpMainMenu->hide();
			}
		}
		else if (state != State_Initializing)
		{
			mpMainMenu->show();
			mpQuitButton->show();
			if (state == State_GameOver) mpContinueButton->setEnabled(false);
			if (mSaveExists) mpLoadGameButton->setEnabled(true);
			else mpLoadGameButton->setEnabled(false);
			mpContinueButton->show();
			mpLoadGameButton->show();
			mpNewGameButton->show();
			mpOptionsButton->show();
			mpMainMenu->activate();
		}
	}
	// Open and close the window for system output
	else if (key == 41)
	{
		if (mpSysOutputWnd->isVisible())
		{
			mpSysOutputWnd->hide();
		}
		else
		{
			mpSysOutputWnd->show();
		}
	}
	// Open and close skill menu
	else if (key == 46)
	{
		if (!mpMainMenu->isVisible() && !mpOptionsMenu->isVisible())
		{
			if (mpSkillMenu->isVisible())
			{
				//this->closeSkillMenu();
			}
			else
			{
				//this->openSkillMenu();
			}
		}
	}
}
//-------------------------------------------------------------------------------------
bool GameGUI::continueGame(const CEGUI::EventArgs &evt)
{
	// Hide main menu and continue the game
	mpMainMenu->hide();

	gpApp->changeState(State_Running);

	mpHUD->show();
	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::loadGame(const CEGUI::EventArgs &evt)
{
	// Hide main menu and continue the game
	mpMainMenu->hide();

	if (gpApp->getState() != State_Initializing)
	{
		gpApp->changeState(State_LoadGame);

		// Reset new game message
		mpTextOutput->setText("VOO");
		mpTextOutput->setAlpha(0.999f);
	}
	else
	{
		gpApp->changeState(State_Loading);
	}
	mpHUD->show();
	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::newGame(const CEGUI::EventArgs &evt)
{
	if (gpApp->getState() == State_Initializing)
	{
		gpApp->changeState(State_Starting);
		mpTextOutput->setAlpha(0.999f);

		// Enable the continue button
		mpContinueButton->setEnabled(true);

		mSaveExists = false;

		mpMainMenu->hide();
		mpSkillMenu->hide();
		
		return true;
	}

	gpApp->changeState(State_Reseting);
	mpContinueButton->setEnabled(true);
	mpMainMenu->hide();

	// Reset new game message
	mpTextOutput->setText("VOO");
	mpTextOutput->setAlpha(0.999f);

	mSaveExists = false;

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::openOptions(const CEGUI::EventArgs &evt)
{
	if (gpApp->getState() != State_Initializing) mbInit = false;
	gpApp->changeState(State_Initializing);

	mpMainMenu->hide();
	restoreSettings();
	mpOptionsMenu->show();
	mpOptionsMenu->activate();

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::quitGame(const CEGUI::EventArgs &evt)
{
	gpApp->changeState(State_Quitting);

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::increaseHealth(const CEGUI::EventArgs &evt)
{
	if(gpApp->mpGameLogic->getCharacter()->buySkill(TREE_HEALTH))
	{
		mpHealthBar->setProgress(mpHealthBar->getProgress() + 0.1f);
		
		int pointsVal = (int) gpApp->mpGameLogic->getCharacter()->getSkillPoints();
		std::string s;
		std::stringstream out;
		out << pointsVal;
		s = out.str();
		mpSP->setText(s);
	}

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::increaseEnergy(const CEGUI::EventArgs &evt)
{
	if(gpApp->mpGameLogic->getCharacter()->buySkill(TREE_ENERGY))
	{
		mpEnergyBar->setProgress(mpEnergyBar->getProgress() + 0.1f);
		
		int pointsVal = (int) gpApp->mpGameLogic->getCharacter()->getSkillPoints();
		std::string s;
		std::stringstream out;
		out << pointsVal;
		s = out.str();
		mpSP->setText(s);
	}
	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::increaseCombat(const CEGUI::EventArgs &evt)
{
	if(gpApp->mpGameLogic->getCharacter()->buySkill(TREE_COMBAT))
	{
		mpCombatBar->setProgress(mpCombatBar->getProgress() + 0.1f);
		
		int pointsVal = (int) gpApp->mpGameLogic->getCharacter()->getSkillPoints();
		std::string s;
		std::stringstream out;
		out << pointsVal;
		s = out.str();
		mpSP->setText(s);
	}
	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::openStoryWindow(const string text, int speakerID)
{
	if(speakerID == 1) this->mpStoryImage->setProperty( "Image", "set:Macaroni image:Macaroni");
	if(speakerID == 0) this->mpStoryImage->setProperty( "Image", "set:Tutor image:Tutor");
	gpApp->changeState(State_Pause);
	this->mpStoryDisplay->setText(text);
	this->mpStoryWindow->show();
	this->mpStoryWindow->activate();

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::storyButton(const CEGUI::EventArgs &evt)
{
	this->mpStoryWindow->hide();
	this->mpStoryWindow->deactivate();

	if(this->mpClassSelection->isVisible()) 
	{
		mpClassSelection->activate();
		return true;
	}
	gpApp->changeState(State_Running);

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::closeSkillMenu(const CEGUI::EventArgs &evt)
{
	mpSkillMenu->hide();
	mpSkillMenu->deactivate();
	gpApp->changeState(State_Running);

	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::cancelOptions(const CEGUI::EventArgs &evt)
{
	if (mbInit)
	{
		gpApp->changeState(State_Initializing);
	}
	else
	{
		gpApp->changeState(State_Pause);
	}

	mpOptionsMenu->hide();

	mpMainMenu->show();
	mpQuitButton->show();
	mpContinueButton->show();
	mpNewGameButton->show();
	mpOptionsButton->show();
	mpMainMenu->activate();

	return true;
}
//------------------------------------------------------------------------------------
/** change class of player 0: none, 1: melee, 2: ranged  */
bool GameGUI::changeClass(int classID)
{
	gpApp->mpGameLogic->getCharacter()->changeClass((Archetype) classID);
	return true;
}

bool GameGUI::selectMelee(const CEGUI::EventArgs &evt)
{
	changeClass(1);
	this->mpClassSelection->hide();
	this->mpClass->deactivate();
	gpApp->changeState(State_Running);

	return true;
}

bool GameGUI::selectRanged(const CEGUI::EventArgs &evt)
{
	changeClass(2);
	this->mpClassSelection->hide();
	this->mpClass->deactivate();
	gpApp->changeState(State_Running);
	return true;
}
//-------------------------------------------------------------------------------------
bool GameGUI::openSkillMenu(const CEGUI::EventArgs &evt)
{
	int charClass = (int) gpApp->mpGameLogic->getCharacter()->getSkillTree()->archetype;

	if (!mpClassSelection->isVisible() && !mpMainMenu->isVisible() && !mpOptionsMenu->isVisible())
	{
		if (mpSkillMenu->isVisible())
		{
			gpApp->changeState(State_Running);
			mpSkillMenu->hide();
			mpSkillMenu->deactivate();
			//if (!mpSysOutputWnd->isVisible()) CEGUI::MouseCursor::getSingleton().hide();
		}
		else
		{
			gpApp->changeState(State_Pause);
			mpSkillMenu->show();

			//CEGUI::MouseCursor::getSingleton().show();
			float skillsProgressFactor = 10.0f;

			//load progress.
			float hProg = (float)gpApp->mpGameLogic->getCharacter()->getSkillTree()->healthTree;
			float eProg = (float)gpApp->mpGameLogic->getCharacter()->getSkillTree()->energyTree;
			float cProg = (float)gpApp->mpGameLogic->getCharacter()->getSkillTree()->combatTree;
	
			mpHealthBar->setProgress(hProg / skillsProgressFactor);
			mpEnergyBar->setProgress(eProg / skillsProgressFactor);
			mpCombatBar->setProgress(cProg / skillsProgressFactor);
				
			//set skill points display
			int pointsVal = (int) gpApp->mpGameLogic->getCharacter()->getSkillPoints();
			std::string s;
			std::stringstream out;
			out << pointsVal;
			s = out.str();
			mpSP->setText(s);

			//set class display
			out = stringstream();
			out << evaluateClass(hProg, eProg, cProg, charClass) << endl;
			s = out.str();
			this->mpClass->setText(s);

			mpSkillMenu->activate();		
		}
	}

	return true;
}
//-------------------------------------------------------------------------------
SettingsManager* GameGUI::getTexts()
{
	return mTexts;
}
//-------------------------------------------------------------------------------
string GameGUI::evaluateClass(float health, float energy, float combat, int classID)
{
	string result = "Soldier";
	float dist = 3.f;

	// if lowbob return first setting
	if(health + energy + combat < dist) return result;

	//ranged classes
	if(classID == 2)
	{
		//health heavy
		if(health > energy + dist && health > combat + dist)
		{
			result = "Coward";
		} 
		//energy heavy
		else if(energy > health+dist && energy > combat + dist)
		{
			result = "Trickster";
		}
		else if(combat > health+dist && combat > energy + dist)
		{
			result = "Cannonslinger";
		}
		else result = "Shooter";

		//combat heavy
	}
	//melee classes
	else 
	{
		//health heavy
		if(health > energy + dist && health > combat + dist)
		{
			result = "Meat-Shield";
		} 
		//energy heavy
		else if(energy > health+dist && energy > combat + dist)
		{
			result = "Fury";
		}
		else if(combat > health+dist && combat > energy + dist)
		{
			result = "Swordsman";
		}
		else result = "Warrior";
	}

	return result;
}
//-------------------------------------------------------------------------------------
bool GameGUI::submitOptions(const CEGUI::EventArgs &evt)
{
	OpenGLConfig *config = mpVideoSettings->getCurOpenGLSettings();

	// Save choosen settings
	config->resolution = CharArrayPtr(new Ogre::String(mpOptionsMenu->getChild("OptionsMenu/ResolutionComboBox")->getText().c_str()));

	config->fsaa = CharArrayPtr(new Ogre::String(mpOptionsMenu->getChild("OptionsMenu/FSAAComboBox")->getText().c_str()));

	CEGUI::Checkbox *checkBox = static_cast<CEGUI::Checkbox*>(mpOptionsMenu->getChild("OptionsMenu/VSyncCheckBox"));
	if (checkBox->isSelected())
	{
		config->vsync = CharArrayPtr(new Ogre::String("Yes"));
	}
	else
	{
		config->vsync = CharArrayPtr(new Ogre::String("No"));
	}

	checkBox = static_cast<CEGUI::Checkbox*>(mpOptionsMenu->getChild("OptionsMenu/FullscreenCheckBox"));
	if (checkBox->isSelected())
	{
		// Change screen settings
		char res[15];
		strcpy(res, config->resolution->c_str());
		char *tok = strtok(res, " x ");
		unsigned width = atoi(tok);
		tok = strtok(0, " x ");
		unsigned int height = atoi(tok);
		mpWindow->setFullscreen(true, width, height);

		config->fullscreen = CharArrayPtr(new Ogre::String("Yes"));
	}
	else
	{
		// Change screen settings
		char res[15];
		strcpy(res, config->resolution->c_str());
		char *tok = strtok(res, " x ");
		unsigned width = atoi(tok);
		tok = strtok(0, " x ");
		unsigned int height = atoi(tok);
		mpWindow->setFullscreen(false, width, height);

		config->fullscreen = CharArrayPtr(new Ogre::String("No"));
	}

	// Go back to main menu
	cancelOptions(evt);

	return true;
}

int GameGUI::activeWindows()
{
	int result = 0;
	
	if (this->mpSkillMenu->isVisible()) result++;
	if (this->mpClassSelection->isVisible()) result++;
	if (this->mpMainMenu->isVisible()) result++;
	if (this->mpStoryWindow->isVisible()) result++;
	if (this->mpOptionsMenu->isVisible()) result++;

	return result;
}